package dhy.com.server;

import dhy.com.config.protocol.MessageCodecSharable;
import dhy.com.config.protocol.ProcotolFrameDecoder;
import dhy.com.container.RpcContainerImpl;
import dhy.com.container.RpcContainerScanner;
import dhy.com.exception.RpcContainerException;
import dhy.com.handler.RpcRequestMessageHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zdh
 */
@Slf4j
public class RpcServer {

    /**
     * rpc容器类
     */
    private final static RpcContainerImpl rpcContainer=new RpcContainerImpl();;

    private static void initRpcServer() {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        RpcRequestMessageHandler RPC_HANDLER = new RpcRequestMessageHandler();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.group(boss, worker);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
                    ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    ch.pipeline().addLast(RPC_HANDLER);
                }
            });
            beforeStart();
            Channel channel = serverBootstrap.bind(8080).sync().channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("server error", e);
        } catch (RpcContainerException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    /**
     * 先扫描所有的标注了Server注解的对象进容器
     */
    private static void beforeStart() throws RpcContainerException {
        RpcContainerScanner rpcContainerScanner=new RpcContainerScanner(rpcContainer);
        rpcContainerScanner.scannerServer();
    }

    public void start()
    {
        initRpcServer();
    }
}
